/****************************************************
* Unity版本：2022.1.21f1c1
* Version：0.1
* Company：DefaultCompany
* 日期：2023/06/20 17:09:21
*****************************************************/

using HHHFramework.MQTT;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClientUI : MonoBehaviour
{
    public InputField port, ipAddress,userID ,userName, password,topicSub,topic,msg;
    public Button connectServerBtn, disConnectServerBtn,sendMsgBtn, Subscribed,unSubScribed;
    public Text tips;

    MqttClient mqttClient;

    public string ClientID { 
        get { return userID.text; } 
        set { userID.text = value ; } }
    void Start()
    {
        connectServerBtn.onClick.AddListener(ConnectBtnClick);
        disConnectServerBtn.onClick.AddListener(DisConnectBtnClick);
        sendMsgBtn.onClick.AddListener(SendMsgBtnClick);
        Subscribed.onClick.AddListener(SubscribeAsyncClick);
        unSubScribed.onClick.AddListener(UnSubscribeAsyncClick);

    }

    private void ConnectBtnClick() {
        mqttClient = new MqttClient(userID.text,userName.text, password.text , ipAddress.text,int.Parse(port.text));
        mqttClient.msgReciveCallBack = MsgRecive;
    }
    private void DisConnectBtnClick()
    {
        mqttClient.Disconnect();
    }
    /// <summary>
    /// ȡ����������
    /// </summary>
    public void UnSubscribeAsyncClick()
    {
        mqttClient.UnsubscribeAsyncEvent(topic.text);
    }

    /// <summary>
    /// ��������
    /// </summary>
    public void SubscribeAsyncClick() {
        mqttClient.SubscribeAsyncEvent(topicSub.text);
    }
    /// <summary>
    /// ������Ϣ
    /// </summary>
    public void SendMsgBtnClick()
    {
        mqttClient.SendMessage(topic.text, msg.text);

    }

    private void MsgRecive(string clientID,string topic,string msg) {
        tips.text += $"topic:{topic}   Msg:{msg}\n";
    }

    private void OnApplicationQuit()
    {
        if (mqttClient!=null) 
            mqttClient.Disconnect();
    }
}
